package com.runvp.common.util.enc;

import com.runvp.common.hex.HexConvert;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESGCMDecryptor1 {




    public static String decrypt(String iv, String key, String tag, String encryptedText) {
        try {
            byte[] ivBytes = Base64.getDecoder().decode(iv);
            byte[] keyBytes = Base64.getDecoder().decode(key);
            byte[] tagBytes = Base64.getDecoder().decode(tag);
            byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);


            SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
            GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, ivBytes);

            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);
            cipher.updateAAD(tagBytes);

            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String iv = HexConvert.str2HexStr("98BPRR4Wve41");
        String key = HexConvert.str2HexStr("BMrcujdO0XDjvOOa");
        String tag = "7130C4C92F60B7EB4D565B1DDFC2559E";
        String encryptedText = "6BE3153AFC79025ACDF03CB38D988927BBF1DB4FCE387729CB19AB13FEC136";

        String decryptedText = decrypt(iv, key, tag, encryptedText);
        System.out.println("Decrypted Text: " + decryptedText);
    }
}